import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../safe_bottom_view.dart';
import 'color.dart';

typedef OnSelectedDate = void Function(String date);
typedef OnCleanDate = void Function(String date);

class DatePickers extends StatefulWidget {
  DatePickers(this.title,
      {this.onSelectedDate,
      this.type = false,
      this.onCleanDate,
      this.selectedDate,
      this.startYear = 1970,
      this.endYear = 2500});

  // 结果返回
  final OnSelectedDate? onSelectedDate;
  final OnCleanDate? onCleanDate;
  final String? selectedDate; //选中的时间
  final int startYear;
  final int endYear;
  final String title;
  final bool type;

  @override
  _DatePickersState createState() => _DatePickersState();
}

class _DatePickersState extends State<DatePickers> {
  //年数组
  List<String>? yearList = [];

  //月数组
  List<String>? monthList = [];

  //天数组
  List<String>? dayList = [];

  //年的索引
  late int yearIndex;

  //月的索引
  late int monthIndex;

  //天的索引
  late int dayIndex;

  //每列的宽度
  double? _columnWidth;

  FixedExtentScrollController? yearScrollController;
  FixedExtentScrollController? monthScrollController;
  FixedExtentScrollController? dayScrollController;

  @override
  void initState() {
    super.initState();

    _columnWidth = ScreenUtil().screenWidth / 3;

    _setupData();

    _initSelectedIndex();
  }

  @override
  void dispose() {
    yearScrollController!.dispose();
    monthScrollController!.dispose();
    dayScrollController!.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          _headerWidget(),
          _datePicker(),
          InkWell(
            onTap: () {
              if (widget.onSelectedDate != null) {
                dayIndex = dayScrollController!.selectedItem;
                String date = yearList![yearIndex] +
                    '-' +
                    monthList![monthIndex].padLeft(2, '0') +
                    '-' +
                    dayList![dayIndex].padLeft(2, '0');
                widget.onSelectedDate!(date);
              }
            },
            child: Container(
                height: 44.w,
                margin: EdgeInsets.only(left: 20.w, right: 20.w),
                decoration: BoxDecoration(
                  color: ColorManager.colorA79485,
                  borderRadius: BorderRadius.all(Radius.circular(2.w)),
                ),
                child: Center(
                  child: Text('确认',
                      style: TextStyle(
                        fontSize: 15.sp,
                        color: Colors.white,
                      )),
                )),
          ),
          SizedBox(
            height: ScreenUtil().bottomBarHeight + 10.w,
          )
        ],
      ),
    );
  }

  ///初始化数据
  void _setupData() {
    for (int i = widget.startYear; i <= widget.endYear; i++) {
      yearList!.add(i.toString());
    }

    for (int i = 1; i <= 12; i++) {
      monthList!.add(i.toString());
    }

    // 初始化天数(当前时间系统时间的天数)
    int year = DateTime.now().year;
    int month;
    if (widget.selectedDate == null || widget.selectedDate!.isEmpty) {
      month = DateTime.now().month;
    } else {
      List<String> date = widget.selectedDate!.split('-');
      month = int.parse(date[1]);
    }

    dayList = _getDayList(year: year, month: month);
  }

  int _getDayCount({int? year, int? month}) {
    int dayCount = DateTime(year!, month! + 1, 0).day;
    return dayCount;
  }

  List<String> _getDayList({int? year, int? month}) {
    List<String> dayList = [];
    int days = _getDayCount(year: year, month: month);
    for (int i = 1; i <= days; i++) {
      dayList.add(i.toString());
    }

    return dayList;
  }

  ///选中年月后更新天
  void _updateDayList() {
    int? year = int.parse(yearList![yearIndex]);
    int? month = int.parse(monthList![monthIndex]);

    setState(() {
      dayList = _getDayList(year: year, month: month);
      // dayIndex=0;
      // if (dayScrollController!.positions.length > 0) {
      //   dayScrollController!.jumpTo(0);
      // }
    });
  }

  ///初始化时间索引
  void _initSelectedIndex() {
    final List uniqueYearList = Set.from(yearList!).toList();
    final List uniqueMonthList = Set.from(monthList!).toList();
    final List uniqueDayList = Set.from(dayList!).toList();

    ///获取索引
    if (widget.selectedDate != null && widget.selectedDate!.isNotEmpty) {
      ///传了选中日期的时候
      List<String> date = widget.selectedDate!.split('-');

      setState(() {
        yearIndex = uniqueYearList.indexOf(date[0]);
        if (date[1].startsWith('0')) {
          String newdata = date[1].split('0')[1];
          monthIndex = uniqueMonthList.indexOf(newdata);
        } else {
          monthIndex = uniqueMonthList.indexOf(date[1]);
        }
        if (date[2].startsWith('0')) {
          String newdata = date[2].split('0')[1];
          dayIndex = uniqueDayList.indexOf(newdata);
        } else {
          dayIndex = uniqueDayList.indexOf(date[2]);
        }
      });
    } else {
      ///没有传选中日期默认当前系统时间
      String year = DateTime.now().year.toString();
      String month = DateTime.now().month.toString();
      String day = DateTime.now().day.toString();

      setState(() {
        yearIndex = uniqueYearList.indexOf(year);
        monthIndex = uniqueMonthList.indexOf(month);
        dayIndex = uniqueDayList.indexOf(day);
      });
    }

    yearScrollController = FixedExtentScrollController(initialItem: yearIndex);
    monthScrollController =
        FixedExtentScrollController(initialItem: monthIndex);
    dayScrollController = FixedExtentScrollController(initialItem: dayIndex);
  }

  Widget _headerWidget() {
    return Container(
      height: 60.w,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            alignment: Alignment.center,
            child: Text(
              widget.title,
              style: TextStyle(fontSize: 16, color: ColorManager.color2A2A2A),
            ),
          ),
          widget.type
              ? Positioned(
                  left: 1,
                  child: FlatButton(
                    child: Text(
                      '清空选择',
                      style: TextStyle(
                          color: ColorManager.color999999, fontSize: 14.sp),
                    ),
                    onPressed: () {
                      widget.onCleanDate!('');
                    },
                  ),
                )
              : Container(),
        ],
      ),
      decoration: BoxDecoration(
        border: Border(
            bottom: BorderSide(
                color: ColorManager.color000000.withOpacity(0.1), width: 0.5)),
      ),
    );
  }

  Widget _datePicker() {
    return Container(
      height: 300.w,
      child: Stack(
        children: [
          Row(
            children: <Widget>[
              Expanded(child: _yearPickerView()),
              Expanded(child: _monthPickerView()),
              Expanded(child: _dayPickerView()),
            ],
          ),
          Container(
            color: ColorManager.colorE5E4E3,
            margin: EdgeInsets.only(top: 130.w),
            height: 0.5,
          ),
          Container(
            color: ColorManager.colorE5E4E3,
            margin: EdgeInsets.only(top: 172.w),
            height: 0.5,
          ),
          // Container(
          //   margin: EdgeInsets.only(top: 78),
          //   child: Row(
          //     children: [
          //       Expanded(
          //         child: Padding(
          //           padding: EdgeInsets.only(left: _columnWidth! - 40, top: 9),
          //           child: Text(
          //             '年',
          //             style: TextStyle(color: Colors.grey, fontSize: 16),
          //             maxLines: 1,
          //           ),
          //         ),
          //       ),
          //       Expanded(
          //         child: Padding(
          //           padding: EdgeInsets.only(left: _columnWidth! - 50, top: 9),
          //           child: Text(
          //             '月',
          //             style: TextStyle(color: Colors.grey, fontSize: 16),
          //             maxLines: 1,
          //           ),
          //         ),
          //       ),
          //       Expanded(
          //         child: Padding(
          //           padding: EdgeInsets.only(left: _columnWidth! - 50, top: 9),
          //           child: Text(
          //             '日',
          //             style: TextStyle(color: Colors.grey, fontSize: 16),
          //             maxLines: 1,
          //           ),
          //         ),
          //       ),
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  ///年
  Widget _yearPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: yearScrollController,
        children: _buildYearWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            yearIndex = index;
          });
          _updateDayList();
        },
        itemExtent: 50,
      ),
    );
  }

  ///月
  Widget _monthPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: monthScrollController,
        children: _buildMonthWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            monthIndex = index;
          });

          _updateDayList();
        },
        itemExtent: 50,
      ),
    );
  }

  ///日
  Widget _dayPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: dayScrollController,
        children: _buildDayWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            dayIndex = index;
          });
        },
        itemExtent: 50,
      ),
    );
  }

  ///年Widget
  List<Widget> _buildYearWidget() {
    List<Widget> yearListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in yearList!) {
      yearListWidget.add(
        Center(
          child: Text(
            '$item 年',
            style: TextStyle(color: ColorManager.color2A2A2A, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return yearListWidget;
  }

  ///月Widget
  List<Widget> _buildMonthWidget() {
    List<Widget> monthListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in monthList!) {
      monthListWidget.add(
        Center(
          child: Text(
            '$item 月',
            style: TextStyle(color: ColorManager.color2A2A2A, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return monthListWidget;
  }

  ///日Widget
  List<Widget> _buildDayWidget() {
    List<Widget> dayListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in dayList!) {
      dayListWidget.add(
        Center(
          child: Text(
            '$item 日',
            style: TextStyle(color: ColorManager.color2A2A2A, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return dayListWidget;
  }
}
